package ExecuteEngine;

import java.util.*;
import parse.*;

public class Tuple {
	public List<Element> tuple = new ArrayList<Element>();
	
	public void addElement(Element e){
		tuple.add(e);
	}
	
	public Tuple(){
	}
	
	public Tuple(Tuple t){
		this.tuple = t.tuple;
	}
	
	public Tuple addTuple(Tuple t){
		for(int i=0; i<t.tuple.size(); i++)
			this.tuple.add(t.tuple.get(i));
		
		return this;
	}
	
	public byte[] tupleToByte(DataItem[] t){
		byte record[];
		int recSize = 0;
		int position = 0;
		
		for(int i=0; i<t.length; i++){
			if(t[i] instanceof IntegerItem)
				recSize += 4;
			else
				recSize += ((VarcharItem)t[i]).value.length();
		}
		
		record = new byte[recSize];
		for(int i=0; i<t.length; i++){
			if(t[i] instanceof IntegerItem){
				byte intRec[] = new byte[4];
				for(int j = 0;j < 4;j++)
					intRec[j] = (byte)((((IntegerItem)t[i]).value) >> (24 - j * 8)); 
				System.arraycopy(intRec, 0, record, position, 4);
				position += 4;
			}
			else{
				int length = ((VarcharItem)t[i]).value.length();
				byte stringRec[] = new byte[length];
				String rec = ((VarcharItem)t[i]).value.toString();
				stringRec = rec.getBytes();
				System.arraycopy(stringRec, 0, record, position, length);
				position += length;
			}
		}
		
		return record;
	}
}
